<template>
  <div class="container">
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="100px" class="ruleForm" status-icon>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="ruleForm.email" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password" />
      </el-form-item>
      <el-form-item class="btn">
        <el-button type="primary" @click="submitForm(ruleFormRef)">登录</el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
      <el-form-item class="link">
        <router-link to="/register">去注册</router-link>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { initLogin } from '@/type/loginData'
import { useStore } from 'vuex'
import $http from '@/request/http'

const $router = useRouter()
const $store = useStore()

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive(new initLogin())

const rules = reactive<FormRules>({
  email: [
    { required: true, message: '邮箱不能为空', trigger: 'blur' },
    { type: 'email', message: '请输入正确邮箱格式', trigger: ['blur', 'change'] },
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 6, max: 12, message: '密码长度在6-12位', trigger: ['blur', 'change'] },
  ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (!valid) return ElMessage.error('表单验证不通过')
    if (valid) {
      const { data: res } = await $http.post('/api/users/login', ruleForm)
      if (res.status === 1) return ElMessage.error(res.message)
      ElMessage.success('登录成功')
      localStorage.setItem('token', res.token)
      $router.push('/index')
      $store.dispatch('user/initUserInfo')
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>

<style scoped lang="less">
.container {
  height: 100%;
  padding-top: 240px;
  background-color: #666;
}
.ruleForm {
  width: 470px;
  height: 260px;
  background-color: #bfa;
  margin: auto;
  border-radius: 10px;
  padding-top: 50px;
  padding-right: 60px;
  .btn {
    margin-top: 30px;
    margin-left: 70px;
  }
  .link {
    margin-left: 115px;
  }
}
</style>
